package com.neusoft.demo.exception;

import com.neusoft.demo.constant.enums.ResultEnum;
import com.neusoft.demo.util.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 *
 * @author BBQ
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)  //申明捕获哪个异常类
    public RestResponse handlerException(Exception e) {
        String desc = StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : e.toString();
        RestResponse response = new RestResponse();
        response.setCode(ResultEnum.CODE_500.getCode());
        response.setMessage(ResultEnum.CODE_500.getMessage());
        response.setAny("desc", desc);
        log.error("全局拦击，具体信息为：", e);
        return response;
    }

    @ExceptionHandler(BusinessException.class)
    public RestResponse handlerBusinessException(BusinessException e) {
        String desc = e.getDesc();
        RestResponse response = new RestResponse();
        response.setCode(e.getCode());
        response.setMessage(e.getMessage());
        response.setAny("desc", desc);
        log.error("业务异常，具体信息为 ", e);
        return response;
    }

    @ExceptionHandler(BindException.class)
    public RestResponse bindException(BindException e) {
        return getResultMap(e.getBindingResult());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RestResponse methodArgumentNotValidException(MethodArgumentNotValidException e) {
        return getResultMap(e.getBindingResult());
    }

    private RestResponse getResultMap(BindingResult bindingResult) {
        RestResponse response = new RestResponse();
        response.setCode(ResultEnum.CODE_400.getCode());
        if (bindingResult != null && bindingResult.getFieldError() != null) {
            StringBuilder error = new StringBuilder();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                error.append(fieldError.getDefaultMessage()).append(";");
            }
            response.setMessage(error.toString());
        }
        log.error("参数异常，具体信息为：{}", response);
        return response;
    }

}
